package com.v.common.log;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 性能日志工具类.
 *
 * @author yeahwell
 */
public class ProfileLoggerUtil {

    private static Logger innerLogger = LoggerFactory.getLogger(ProfileLoggerUtil.class);
    private static Logger loggerIn = LoggerFactory.getLogger(LogTypeEnum.LOG_SERVICEIN.val);
    private static Logger loggerOut = LoggerFactory.getLogger(LogTypeEnum.LOG_SERVICEOUT.val);
    private static Logger loggerDal = LoggerFactory.getLogger(LogTypeEnum.LOG_MONITORDB.val);
    private static Logger loggerMonitorCache = LoggerFactory.getLogger(LogTypeEnum.LOG_MONITORCACHE.val);
    private static String SEPARATOR = ";";

    private ProfileLoggerUtil() {
    }

    public static Logger in() {
        return loggerIn;
    }

    public static Logger out() {
        return loggerOut;
    }

    public static Logger dal() {
        return loggerDal;
    }

    public static Logger monitorCache() {
        return loggerMonitorCache;
    }

    public static void inlog(String serviceName, long startTime, boolean isSuccess, String errorCode, String traceId, String businessName) {
        log(loggerIn, serviceName, startTime, isSuccess, errorCode, traceId, businessName);
    }

    public static void outlog(String serviceName, long startTime, boolean isSuccess, String errorCode, String traceId, String businessName) {
        log(loggerOut, serviceName, startTime, isSuccess, errorCode, traceId, businessName);
    }

    public static void dallog(String serviceName, long startTime, boolean isSuccess, String errorCode, String traceId, String businessName) {
        log(loggerDal, serviceName, startTime, isSuccess, errorCode, traceId, businessName);
    }

    public static void monitorCachelog(String serviceName, long startTime, boolean isSuccess, String errorCode, String traceId, String businessName) {
        log(loggerMonitorCache, serviceName, startTime, isSuccess, errorCode, traceId, businessName);
    }

    private static void log(Logger logger, String serviceName, long startTime, boolean isSuccess, String errorCode, String traceId, String businessName) {
        try {
            long time = System.currentTimeMillis() - startTime;
            StringBuffer sb = new StringBuffer();
            sb.append(serviceName == null ? "" : serviceName).append(SEPARATOR);
            sb.append(time).append(SEPARATOR);
            sb.append(isSuccess ? "Y" : "N").append(SEPARATOR);
            sb.append(errorCode == null ? "" : errorCode).append(SEPARATOR);
            sb.append(traceId == null ? "" : traceId).append(SEPARATOR);
            sb.append(businessName).append(SEPARATOR);
            logger.info(sb.toString());
        } catch (Exception e) {
            innerLogger.error("serviceName: {}, traceId: {}, businessName:{} ", serviceName, traceId, businessName, e);
        }
    }
}
